package com.yangli.leecode.b;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ly
 * @description
 * @data 2022/4/29
 */
public class LetterCombinations {
    public static void main(String[] args) {
        LetterCombinations letterCombinations = new LetterCombinations();
        System.out.println(letterCombinations.letterCombinations("234"));
    }

    static Map<Character, List<String>> init = new HashMap<>();

    static {
        init.put('2', List.of("a", "b", "c"));
        init.put('3', List.of("d", "e", "f"));
        init.put('4', List.of("g", "h", "i"));
        init.put('5', List.of("j", "k", "l"));
        init.put('6', List.of("m", "n", "o"));
        init.put('7', List.of("p", "q", "r", "s"));
        init.put('8', List.of("t", "u", "v"));
        init.put('9', List.of("w", "x", "y", "z"));
    }

    public List<String> letterCombinations(String digits) {
        int length = digits.length();
        if (length == 0) {
            return Collections.emptyList();
        }
        List<StringBuilder> res = new ArrayList<StringBuilder>();
        for (int i = 0; i < length; ++i) {
            res = add(res, init.get(digits.charAt(i)));
        }
        return res.stream().map(StringBuilder::toString).collect(Collectors.toList());

    }

    public List<StringBuilder> add(List<StringBuilder> res, List<String> data) {
        if (res.size() == 0) {
            data.forEach(x -> {
                res.add(new StringBuilder(x));
            });
            return res;
        }
        List<StringBuilder> combine = new ArrayList<StringBuilder>(res.size() * data.size());
        for (StringBuilder stringBuilder : res) {
            data.forEach(x -> {
                StringBuilder temp = new StringBuilder(stringBuilder);
                combine.add(temp.append(x));
            });
        }
        return combine;
    }
}
